import * as request from '../constant/fetch-request'
import HTTP_CODE from '../constant/http-code'
import { message } from 'antd'

export const register = (user, callback) => {
  const DEFAULT_ORG = 1
  user.org = DEFAULT_ORG
  const deviceData = JSON.parse(localStorage.getItem('pair_4th_data'))
  return () => {
    (async () => {
      const res = await request.post('./api/users/register', { ...deviceData, ...user })
      if (res.status === HTTP_CODE.CREATED) {
        message.success('注册成功')
        localStorage.setItem('pair_4th_user', JSON.stringify(res.body))
        callback()
      }
    })()
  }
}
export const joinActivity = (userDetail, callback) => {
  const deviceData = JSON.parse(localStorage.getItem('pair_4th_data'))
  const user = JSON.parse(localStorage.getItem('pair_4th_user'))
  userDetail.recuritMessage = userDetail.recuritMessage ? userDetail.recuritMessage.join(',') : ''
  return () => {
    (async () => {
      const res = await request.update('./api/users', { ...userDetail, ...deviceData, ...user })
      if (res.status === HTTP_CODE.NO_CONTENT) {
        callback()
      }
    })()
  }
}

export const usernameLogin = (user, callback) => {
  return () => {
    (async () => {
      const res = await request.post('./api/users/login', user)
      if (res.status === HTTP_CODE.OK) {
        localStorage.setItem('pair_4th_user', JSON.stringify(res.body))
        callback()
      }
    })()
  }
}
